<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2020/09/18
 * Time: 15:56
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\cha;


use app\admin\controller\BaseController;
use app\common\model\ChannelCarrier;
use app\common\service\logistics\ChannelService;
use think\facade\Validate;

class CarrierController extends BaseController
{
    /**
     * 承运商列表
     * @date 2020/09/18
     * @author longli
     */
    public function index()
    {
        if(!$this->request->isAjax()) return $this->fetch('index');
        $this->assign('list', ChannelCarrier::order("sort desc,carrier_name")->select());
        return $this->fetch('lists');
    }

    /**
     * 更新承运商
     * @date 2020/09/18
     * @author longli
     */
    public function update()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'carrier_name'  => 'require|unique:channel_carrier,carrier_name',
            ],[
                'carrier_name.require' => '承运商名称必填',
                'carrier_name.unique' => '承运商已存在',
            ]);
            $data = $this->request->post();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ChannelCarrier::STATUS_N;
        }
        else
        {
            $validate = Validate::make([
                'carrier_id'  => 'require',
            ],[
                'carrier_id.require' => '非法请求',
            ]);
            $data = $this->request->get();
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        ChannelService::getInstance()->addCarrier($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 录入承运商
     * @date 2020/09/18
     * @author longli
     */
    public function add()
    {
        $this->assign("pay_type", ChannelCarrier::$PAY_TYPE);
        $carrierId = $this->request->request("carrier_id");
        if(!empty($carrierId)) $this->assign("carrier", ChannelCarrier::get($carrierId));
        return $this->fetch("add");
    }

    /**
     * 删除承运商
     * @date 2020/09/18
     * @author longli
     */
    public function delete()
    {
        $carrierId = $this->request->request("ids");
        if(empty($carrierId)) $this->error('参数错误');
        ChannelCarrier::destroy($carrierId);
        $this->success('删除成功');
    }
}